package cn.com.dhcc.app.pub.core.interceptor;

import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;

import cn.com.dhcc.app.core.annotation.WsdNoNeedLogin;
import cn.com.dhcc.app.core.base.BaseController;
import cn.com.dhcc.app.core.base.InterceptorBean;
import cn.com.dhcc.app.core.base.log.LogType;
import cn.com.dhcc.app.core.base.user.LoginUser;
import cn.com.dhcc.app.core.component.log.Log;
import cn.com.dhcc.app.core.exception.ServiceException;
import cn.com.dhcc.app.core.interceptor.InterceptorArgs;
import cn.com.dhcc.app.core.tag.CommonStaticCode.ENTITY_STATUS;
import cn.com.dhcc.app.core.util.CollectionUtil;
import cn.com.dhcc.app.core.util.NetUtil;
import cn.com.dhcc.app.pub.core.AppPara.UAMS;
import cn.com.dhcc.app.pub.module.authmgr.vo.RoleInfoInner;
import cn.com.dhcc.app.pub.module.login.vo.LoginCustomData;
import cn.com.dhcc.sfm.service.uums.UserInfo;

/**
 * 插入单点登录对象
 * 
 * @日期：2012-12-14下午11:21:12
 * @作者：乔兵
 * @版权所有：东华软件
 * @版本：1.0
 */
@Component
public class InjectLoginUserInterceptor extends InterceptorBean {

	private static Logger logger = Log.getLogger(LogType.SYSINNER);

	@Override
	public SIGNAL beforeControllerMethodExecute(InterceptorArgs interceptorArgs) {
		HandlerMethod handlerMethod = interceptorArgs.getHandlerMethod();
		HttpServletRequest request = interceptorArgs.getRequest();
		if (request == null || request.getMethod() == null) {
			return SIGNAL.CONTINUE;
		}
		//无需登录权限认证
		if (null != handlerMethod.getMethodAnnotation(WsdNoNeedLogin.class)) {
			logger.info("佚名资源：" + request.getRequestURI());
			return SIGNAL.CONTINUE;
		} else {
			try {
				injectSsoUser(request, interceptorArgs);
			} catch (Exception e) {
				return SIGNAL.STOP;
			}
			return SIGNAL.CONTINUE;
		}
	}
	@Override
	public SIGNAL interceptorExecuteErrorSignal(Exception beforeControllerMethodExecuteException) {
		return SIGNAL.STOP;
	}
	public static void injectSsoUser(HttpServletRequest request,InterceptorArgs interceptorArgs) throws ServiceException{
		//从单点登录获取登录用户对象
		LoginUser loginUser = interceptorArgs.getLoginUser();
		if(UAMS.SSO_ENABLED){
			//单点登录每次都去取，防止统一退出和用户切换无法感知
			loginUser = getLoginUserFromSsoUser(request);
			BaseController.putCurrentUserInfoToSession(loginUser, request.getSession());
			interceptorArgs.setLoginUser(loginUser);
		}else{
			loginUser = BaseController.getCurrentUserInfo(request.getSession());
			interceptorArgs.setLoginUser(loginUser);
		}
		
	}  
	public static LoginUser getLoginUserFromSsoUser(HttpServletRequest request) throws ServiceException{
		LoginUser ssoUser = null;
		//注入角色 水资源原有角色需要通过岗位获取，新的统一用户管理直接获取
		//水资源的用户管理
		if(UAMS.isSLUAMS()){
			UserInfo userInfoSl = cn.gov.mwr.sso.client.util.SsoUtil.getUserInfo(request);
			if(userInfoSl!=null){
				ssoUser = new LoginUser();
				LoginCustomData customData = new LoginCustomData();
				ssoUser.setCustomData(customData);
				customData.setSsoRawUserInfo(userInfoSl);
				ssoUser.setId(userInfoSl.getUserCode());
				ssoUser.setUserName(userInfoSl.getUserName());
				ssoUser.setUserCode(userInfoSl.getUserCode());
				customData.setDepCode(userInfoSl.getDepCode());
				customData.setOrgCode(userInfoSl.getOrgCode());
				customData.setAdminOrgCode(userInfoSl.getAdminOrgCode());
				customData.setInnerRoles(changeToAppRoinfoList(userInfoSl.getRoleInfoList()));
			}
		}else{
			throw new ServiceException("单点登录类型错误");
		}
		if(ssoUser!=null){
			ssoUser.setFromSso(true);
			ssoUser.setIp(NetUtil.getRemoteIp(request));
			ssoUser.setLoginTime(new Date());
			ssoUser.setSuperAdmin(false);
			LoginCustomData customData = (LoginCustomData) ssoUser.getCustomData();
			if(customData!=null){
				ssoUser.setAuthUserTypes(LoginCustomData.getLoginUserTypeFromUserRole(customData.getInnerRoles()));
			}
		}
		
		return ssoUser;
	}
	/**
	 * 将接口的角色对象转换成框架内部的角色对象
	 */
    private static List<RoleInfoInner> changeToAppRoinfoList(List<cn.com.dhcc.sfm.service.uums.RoleInfo> roleInfos ){
    	List<RoleInfoInner> appRoleInfos = null;
    	if(CollectionUtil.hasElement(roleInfos)){
    		appRoleInfos = new ArrayList<RoleInfoInner>();
    		for (Iterator<cn.com.dhcc.sfm.service.uums.RoleInfo> iterator = roleInfos.iterator(); iterator
					.hasNext();) {
				cn.com.dhcc.sfm.service.uums.RoleInfo roleInfo = iterator.next();
				RoleInfoInner appRoleInfo = new RoleInfoInner();
				if(ENTITY_STATUS.ENABLE.getCode().equals(roleInfo.getStatus())){
					appRoleInfo.setRoleCode(roleInfo.getRoleCode());
					appRoleInfo.setRoleType(roleInfo.getRoleType()+"");
					appRoleInfo.setRoleName(roleInfo.getRoleName());
					appRoleInfo.setOrgCode(roleInfo.getOrgCode());
					appRoleInfos.add(appRoleInfo);
				}
			}
    	}
    	return appRoleInfos;
    }
}
